#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>

#include <stdio.h>   /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h>  /* _exit, fork */
#include <stdlib.h>  /* exit */
#include <errno.h>   /* errno */
 
int main(void)
{
   pid_t  pid;
 
   pid = fork();
   if (pid == -1)
   {   
      fprintf(stderr, "can't fork, error %d\n", errno);
      exit(EXIT_FAILURE);
   }
 
   if (pid == 0)
   {
      puts ("FILHO EXECUTANDO");
      printf("MEU PID: %d & PID DO MEU PAI: %d \n", getpid(), getppid());
      int j;
      for (j = 0; j < 2; j++)
      {
	 printf("QUEM É 2? %d\n", getpid());
         printf("numero de filhos: %d\n", j);
	 printf("ESPERA %d\n", getpid());
         sleep(1);
      }
       printf("Terminando %d\n", getpid());
      _exit(0);  /* Note that we do not use exit() */
   }
   else
   { 
 
      /* When fork() returns a positive number, we are in the parent process
       * (the fork return value is the PID of the newly created child process)
       * Again we count up to ten.
       */
      puts ("PAI EXECUTANDO");
      printf("MEU PID: %d & PID DO MEU PAI: %d\n", getpid(), getppid());
      int i;
      for (i = 0; i < 2; i++)
      {
	 printf("QUEM É 1? %d\n", getpid());
         printf("numero de pais: %d\n", i);
	 printf("ESPERA %d\n", getpid());
         sleep(1);
      }
      printf("EPERANDO O FILHO\n");
      wait(1); //esperando o filho terminar
      printf("Terminando %d\n", getpid());
      exit(0);
   }
   return 0;
}
